package cn.dankal.flyaudio.personal;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import java.util.List;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.common.qiniu.UploadListener;
import cn.dankal.basiclib.common.upload.ali.AliUIDisplayer;
import cn.dankal.basiclib.common.upload.ali.AliUploadHelper;
import cn.dankal.basiclib.pojo.ProductDetailAttrEntity;
import cn.dankal.basiclib.pojo.ProductDetailItemEntity;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.GlideEngine;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.util.UriUtils;
import cn.dankal.basiclib.widget.TipDialog;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.ImgAdapter;
import cn.dankal.flyaudio.contract.MyCommentContract;
import cn.dankal.flyaudio.friend.pickimage.StringUtil;
import cn.dankal.flyaudio.friend.utils.takevideo.utils.LogUtils;
import cn.dankal.flyaudio.oss.view.AliUploadActivity;
import cn.dankal.flyaudio.presenter.MyCommentPresenter;
import cn.dankal.flyaudio.store.PayResultActivity;

/**
 * <pre>
 *     e-mail : junfeng.nie@duntech.com.cn
 *     time   : 19/7/2020
 *     desc   :
 *     version: cn.dankal.flyaudio.personal
 *     Copyright: Copyright（c）2018
 *     Company: 我的评价
 * </pre>
 *
 * @author niejunfeng
 */
public class MyCommentActivity extends AliUploadActivity implements MyCommentContract.View, View.OnClickListener {
    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_comment;
    }

    ImgAdapter mImgAdapter;
    TextView tvImgSize, tvTextSize;
    EditText editContent;
    int imgPosition;
    RecyclerView recyclerView;
    private String productUuid;
    private String uuid;
    private LinearLayout llGood, llAverage, llPoor;
    private ImageView ivGood, ivAverage, ivPoor;
    private TextView tvGood, tvAverage, tvPoor, tvContent, tvTitle;
    private ImageView productImg;
    private String type = "";
    private String title = "";
    private String img = "";
    private String typeContent = "";//规格内容
    private MyCommentPresenter myCollectionPresenter;
    private List<ProductDetailItemEntity> productDetailItemEntities;
    private int position = 0;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myCollectionPresenter.detachView();
    }

    @Override
    protected void initComponents() {
        super.initComponents();
        position = 0;
        uuid = getIntent().getStringExtra("id");
        String json = getIntent().getStringExtra("model");
        productDetailItemEntities = JSON.parseArray(json, ProductDetailItemEntity.class);

        myCollectionPresenter = new MyCommentPresenter();
        tvTitle = findViewById(R.id.tv_comment_title);
        myCollectionPresenter.attachView(this);
        productImg = findViewById(R.id.iv_icon);
        llGood = findViewById(R.id.ll_good);
        llAverage = findViewById(R.id.ll_average);
        llPoor = findViewById(R.id.ll_poor);

        tvContent = findViewById(R.id.tv_content);

        tvAverage = findViewById(R.id.tv_average);
        tvGood = findViewById(R.id.tv_good);
        tvPoor = findViewById(R.id.tv_poor);
        ivAverage = findViewById(R.id.iv_average);
        ivGood = findViewById(R.id.iv_good);
        ivPoor = findViewById(R.id.iv_poor);

        llPoor.setOnClickListener(this);
        llAverage.setOnClickListener(this);
        llGood.setOnClickListener(this);
        findViewById(R.id.iv_onback).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mImgAdapter = new ImgAdapter();
        recyclerView = findViewById(R.id.rv_pic);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL,
                false));
        recyclerView.setAdapter(mImgAdapter);

        tvImgSize = findViewById(R.id.tv_img_size);
        editContent = findViewById(R.id.edit_content);
        tvTextSize = findViewById(R.id.tv_text_size);

        findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!StringUtil.isEmpty(editContent.getText().toString().trim())) {
                    if (!StringUtil.isEmpty(type)) {
                        showLoadingDialog();
                        if (mImgAdapter.getDatas().size() != 0) {
                            elements.clear();
                            for (String data : mImgAdapter.getDatas()) {
                                elements.add(Uri.parse(data));
                            }

                            for (String data : mImgAdapter.getDatas()) {
                                String objectName = "fg_" + DKUserManager.getUserInfo().getId() + "_" + System.currentTimeMillis() + ".jpg";
                                finalKeys.add(objectName);
                                mService.asyncPutData(objectName, data);
                            }
                        } else {
                            doReport();
                        }


                    } else {
                        ToastUtils.showShort("请评分");
                    }
                } else {
                    ToastUtils.showShort("说点什么吧");
                }

            }
        });
        editContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tvTextSize.setText(s.length() + "/500");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        LiveEventBus.get("addImg", int.class).observe(this,
                new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        if (StringUtil.isEmpty(mImgAdapter.getDatas().get(integer))) {
                            //添加图片
                            open();
                        }
                    }
                });

        LiveEventBus.get("deleteImg", int.class).observe(this,
                new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        LogUtils.e("deleteImg");

                        mImgAdapter.getDatas().remove(mImgAdapter.getDatas().get(integer));
                        if (mImgAdapter.getDatas().size() != 0) {
                            if (!StringUtil.isEmpty(mImgAdapter.getDatas().get(mImgAdapter.getDatas().size() - 1))) {
                                mImgAdapter.addData("");
                            }
                        }
                        mImgAdapter.notifyDataSetChanged();
                        setTextSize();
                    }
                });
        setData();
    }

    private void doReport(){
        for (String img : finalKeys) {
            if (TextUtils.isEmpty(img)) {
                finalKeys.remove(img);
            }
        }
        if (finalKeys.isEmpty()) {
            ToastUtils.showShort("请上传图片!");
//            finalKeys.add("");
            return;
        }
        myCollectionPresenter.getEvaluate(uuid, productUuid, editContent.getText().toString(),
                type, finalKeys);
    }
    private void setData() {
        List<ProductDetailAttrEntity> attrEntities =
                productDetailItemEntities.get(position).getAttrList();
        llGood.callOnClick();
        img = productDetailItemEntities.get(position).getImgUrl();
        productUuid = productDetailItemEntities.get(position).getProductUuid();

        mImgAdapter.clearData();
        mImgAdapter.addData("");
        editContent.setText("");
        title = productDetailItemEntities.get(position).getProductName();

        StringBuilder sb = new StringBuilder();
        for (ProductDetailAttrEntity attrEntity : attrEntities) {
            sb.append(attrEntity.getAttrValue());
            sb.append("  ");
        }
        typeContent = sb.toString();
        tvContent.setText(typeContent);
        tvTitle.setText(title);
        Glide.with(this).load(img).into(productImg);
    }

    private void open() {

        PictureSelector.create(ActivityUtils.getTopActivity())
                .openGallery(PictureMimeType.ofImage())
//                .selectionMode(PictureConfig.SINGLE)
                .maxSelectNum(maxPosition-selectPosition)
                .loadImageEngine(GlideEngine.Companion.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {

                    @Override
                    public void onResult(List<LocalMedia> result) {
                        // 例如 LocalMedia 里面返回五种path
                        // 1.media.getPath(); 原图path，但在Android Q版本上返回的是content:// Uri类型
                        // 2.media.getCutPath();裁剪后path，需判断media.isCut();切勿直接使用
                        // 3.media.getCompressPath();压缩后path，需判断media.isCompressed();切勿直接使用
                        // 4.media.getOriginalPath()); media.isOriginal());为true时此字段才有值
                        // 5.media.getAndroidQToPath();Android Q版本特有返回的字段，但如果开启了压缩或裁剪还是取裁剪或压缩路
                        // 径；注意：.isAndroidQTransform(false);此字段将返回空
                        // 如果同时开启裁剪和压缩，则取压缩路径为准因为是先裁剪后压缩
                        // TODO 可以通过PictureSelectorExternalUtils.getExifInterface();方法获取一些额外的资源信息，
                        //  如旋转角度、经纬度等信息
                        String url = "";
                        for (LocalMedia media : result) {
                            //Android Q 特有Path:
                            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
//                                upload(new File(media.getAndroidQToPath()));
                                url = media.getAndroidQToPath();
                            } else {
                                if (media.isCompressed()) {
                                    //是否压缩
//                                    upload(new File(media.getCompressPath()));
                                    url = media.getCompressPath();
                                } else {
                                    if (media.isOriginal()) {
                                        //是否开启原图
//                                        upload(new File(media.getOriginalPath()));
                                        url = media.getOriginalPath();
                                    } else {
//                                        upload(new File(media.getPath()));
                                        url = media.getPath();
                                    }
                                }
                            }

                            if (mImgAdapter.getDatas().size() < 7) {
                                mImgAdapter.remove(mImgAdapter.getDatas().size() - 1);
                                mImgAdapter.addData(url);
                                if (mImgAdapter.getDatas().size() < 6) {
                                    if (!StringUtil.isEmpty(mImgAdapter.getDatas().get(mImgAdapter.getDatas().size() - 1))) {
                                        mImgAdapter.addData("");
                                    }
                                }
                            }
                            setTextSize();
                            mImgAdapter.notifyDataSetChanged();
                        }

                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    private int selectPosition = 0;
    private int maxPosition = 6;
    private void setTextSize() {
        if (mImgAdapter.getDatas().size() < 6) {
            selectPosition = mImgAdapter.getDatas().size() - 1;
            tvImgSize.setText("上传图片（" + (mImgAdapter.getDatas().size() - 1) + "/6）");
        } else {
            if (StringUtil.isEmpty(mImgAdapter.getDatas().get(5))) {
                selectPosition = mImgAdapter.getDatas().size() - 1;
                tvImgSize.setText("上传图片（" + (mImgAdapter.getDatas().size() - 1) + "/6）");
            } else {
                selectPosition = mImgAdapter.getDatas().size();
                tvImgSize.setText("上传图片（" + (mImgAdapter.getDatas().size()) + "/6）");
            }
        }
    }


    @Override
    public void onSuccess() {
        ToastUtils.showShort("评价成功");
        if (position == productDetailItemEntities.size() - 1) {
            LiveEventBus.get("RefreshOrder", String.class).post("1");
            Intent jump = new Intent(ActivityUtils.getTopActivity(), PayResultActivity.class);
            jump.putExtra("type", "1");
            jump.putExtra("uuid", productUuid);
//        jump.putExtra("isPaySuccess", true);
//        jump.putExtra("orderUuid", mCreateOrderPreviewEntity.getUuid());
            ActivityUtils.startActivity(jump);
            finish();
        } else {
            position++;
            setData();
        }
    }

    @Override
    public void onError() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_average:
                setViewFalse();

                type = "AVERAGE";

                ivAverage.setImageResource(R.mipmap.ic_ping_02);
                tvAverage.setTextColor(getResources().getColor(R.color.color_0085B4));
                break;
            case R.id.ll_good:
                setViewFalse();
                type = "GOOD";
                ivGood.setImageResource(R.mipmap.ic_ping_01);
                tvGood.setTextColor(getResources().getColor(R.color.color_0085B4));
                break;
            case R.id.ll_poor:
                setViewFalse();
                type = "POOR";
                ivPoor.setImageResource(R.mipmap.ic_ping_03);
                tvPoor.setTextColor(getResources().getColor(R.color.color_0085B4));
                break;
        }
    }

    private void setViewFalse() {
        ivPoor.setImageResource(R.mipmap.ic_ping_06);
        ivAverage.setImageResource(R.mipmap.ic_ping_05);
        ivGood.setImageResource(R.mipmap.ic_ping_04);

        tvPoor.setTextColor(getResources().getColor(R.color.color99));
        tvGood.setTextColor(getResources().getColor(R.color.color99));
        tvAverage.setTextColor(getResources().getColor(R.color.color99));
    }

    @Override
    public void uploadComplete() {
//        super.uploadComplete();
        doReport();
    }
}
